<?php
namespace app\admin\controller;

use controller\BasicAdmin;
use service\FileService;
use think\View;

/**
 * 插件助手控制器
 * Class Plugs
 * @package app\admin\controller
 * @author Anyon <zoujingli@qq.com>
 * @date 2017/02/21
 */
class Plugs extends BasicAdmin
{

    /**
     * 默认检查用户登录状态
     * @var bool
     */
    public $checkLogin = false;

    /**
     * 默认检查节点访问权限
     * @var bool
     */
    public $checkAuth = false;

    /**
     * 文件上传
     * @return View
     */
    public function upfile()
    {
        $types = $this->request->get('type', 'jpg,png');
        $mode = $this->request->get('mode', 'one');
        $this->assign('mode', $mode);
        $this->assign('types', $types);
        $this->assign('uptype', 'local');
        $this->assign('mimes', FileService::getFileMine($types));
        $this->assign('field', $this->request->get('field', 'file'));
        return view();
    }

    /**
     * 通用文件上传
     * @return string
     */
    public function upload()
    {
        if ($this->request->isPost()) {
            $md5s = str_split($this->request->post('md5'), 16);
            if (($info = $this->request->file('file')->move('static' . DS . 'upload' . DS . $md5s[0], $md5s[1], true))) {
                $filename = join('/', $md5s) . '.' . $info->getExtension();
                $site_url = FileService::getFileUrl($filename, 'local');
                if ($site_url) {
                    //存入数据库
                    $data['md5'] = $this->request->post('md5');
                    $data['ext'] = $info->getExtension();
                    $data['base_url'] = $site_url;
                    $data['create_time'] = NOW_TIME;
                    db('SystemFile')->insert($data);
                    //返回成功的上传结果
                    return json(['data' => ['site_url' => $site_url], 'code' => 'SUCCESS']);
                }
            }
        }
        return json(['code' => 'ERROR']);
    }

    /**
     * 文件状态检查
     */
    public function upstate()
    {
        $post = $this->request->post();
        $filename = join('/', str_split($post['md5'], 16)) . '.' . pathinfo($post['filename'], PATHINFO_EXTENSION);
        // 检查文件是否已上传
        if (($site_url = FileService::getFileUrl($filename))) {
            $this->result(['site_url' => $site_url], 'IS_FOUND');
        }
        // 需要上传文件，生成上传配置参数
        $config = ['uptype' => $post['uptype'], 'file_url' => $filename];
        switch (strtolower($post['uptype'])) {
            case 'local':
                $config['server'] = FileService::getUploadLocalUrl();
                break;
        }
        $this->result($config, 'NOT_FOUND');
    }

    /**
     * 字体图标
     */
    public function icon()
    {
        $this->assign('field', $this->request->get('field', 'icon'));
        return view();
    }
}
